<!DOCTYPE html>
<html lang="en" xml:lang="en">

<head>
    <meta charset="utf-8"/>
    <title>Reference Image and Camera Settings</title>
        
    <style>
        h1 {font-size: 2em;}
        h2 {font-size: 1.5em; margin-block-start: 0.0em; margin-block-end: 0.2em;}
        h3 {font-size: 1.2em;}
        p {font-size: 1em;}

        input[type=number] {
            width: 60px;
            margin-right: 10px;
            padding: 3px 5px;
            display: inline-block;
            border: 1px solid #ccc;
            font-size: 16px;
            vertical-align: middle;
        }

        input:out-of-range {
            background-color: rgba(255, 0, 0, 0.25);
            border: 1px solid red;
        }

        input:invalid {
            background-color: rgba(255, 0, 0, 0.25);
            border: 1px solid red;
        }

        .expert {
            background-color: #ffefef;
            font-size: 16px;
        }

        .button {
            padding: 5px 10px;
            font-size: 16px;
        }

        th, td {
            padding: 5px 5px 5px 5px;
        }

        table {
            width: 660px;
            padding: 5px;
        }

        .tooltip {
            position: relative;
            display: inline-block;
        }

        .tooltip .tooltiptext {
            visibility: hidden;
            width: 460px;
            background-color: #fcfcfc;

            padding: 5px;
            padding-bottom: 0;

            border: solid black 2px; 

            /* Position the tooltip */
            position: absolute;
            z-index: 1;
            top: 100%;
            left: 520%;
            margin-left: -600px;
        }

        .tooltip:hover .tooltiptext {
            visibility: visible;
        }

        .tooltip-content {
            width: calc(100% - 2px);
            height: calc(100% - 2px);
            padding: 1px;
        }

        #overlay {
            position: fixed;
            display: none;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0,0,0,0.8);
            z-index: 2;
        }

        #overlaytext{
            position: absolute;
            top: 50%;
            left: 50%;
            font-size: 150%;
            color: white;
            transform: translate(-50%,-50%);
            -ms-transform: translate(-50%,-50%);
        }
    </style>

    <link rel="stylesheet" href="mkdocs_theme.css?v=$COMMIT_HASH" />
    <link rel="stylesheet" href="mkdocs_theme_extra.css?v=$COMMIT_HASH" />
    <link rel="stylesheet" href="github.min.css?v=$COMMIT_HASH" />

    <link href="firework.css?v=$COMMIT_HASH" rel="stylesheet">

    <script type="text/javascript" src="common.js?v=$COMMIT_HASH"></script>
    <script type="text/javascript" src="jquery-3.6.0.min.js?v=$COMMIT_HASH"></script>
    <script type="text/javascript" src="firework.js?v=$COMMIT_HASH"></script>

</head>

<body style="font-family: arial; padding: 0px 10px;">
    <div id="overlay">
        <div id="overlaytext"></div>
    </div>

    <h2>Reference Image and Camera Settings</h2>
    <details id="desc_details" style="font-size:16px">
        <summary><b>CLICK HERE</b> for usage description. More infos in documentation: 
                <a href=https://jomjol.github.io/AI-on-the-edge-device-docs/Reference-Image/ target=_blank>Reference Image</a>
        </summary>
        <p>
            The reference image is the base image on which the alignment markers, digit ROIs and anlog ROIs will be defined.
        </p>        
        <p>
            Initially the currently saved reference image is shown. If you start with a setup from scratch, a default image is shown as a placeholder.
            Use the button <b>"Create New Reference / Change Camera Settings"</b> to start the creation of your own reference image. After clicking the button, the camera will take a
            photo using the configured parameters. This will be your new reference image. With the button <b>"Update Reference Image"</b> you can update the image again.
        </p>        
        <p>
            To have a reliable evaluation processing, it is mandatory to have the digit ROIs horizontally aligned. Using the two input fields "Rotation angle" and
            "(Fine-tune)" the image can be rotated in both directions. The resulting rotation angle is used to pre-rotate the image before
            the alignment algorithm is processed to compensate only small misalignments (See next step Alignment Markers). Further information can be found in documenation:
            <a href=https://jomjol.github.io/AI-on-the-edge-device-docs/Reference-Image/ target=_blank>Reference Image</a>
        </p>
        <p>
            After setting up your reference image don't forget to save with the <b>"Save new Reference Image and Camera Settings"</b> button!<br><br>
            <b>NOTE:</b> There is no need to perform a reboot after every saving or step. It's sufficient to reboot after all configuration steps 
            (reference image, alignment, ROI configuration) are completed to activate new configuration.
        </p>
    </details>
    <hr>

    <input class="button" type="button" id="showcurrentreference" disabled value="Reset and show current Reference and Camera Settings" onclick="showReference()"><br><br>
    <input class="button" type="button" id="startreference" value="Create New Reference / Change Camera Settings" onclick="doTakeReference()">
    <hr>

    <input style="margin-top:12px; margin-bottom:12px; color:black" type="checkbox" id="ExpertModus_enabled" value="1"  onclick='UpdateExpertModus()' unchecked>
    <label for="ExpertModus_enabled">Show Expert Parameters</label> 

    <table style="width: 100%">
        <colgroup>
            <col span="1" style="width: 12%;">
            <col span="1" style="width: 15%;">
            <col span="1" style="width: 3%;">
            <col span="1" style="width: 18%;">
            <col span="1" style="width: 10%;">
            <col span="1" style="width: 3%;">
        </colgroup>
		
        <tr class="expert">
			<td class="indent1">
				<class id="TakeImage_CamZoom_text" style="color:black;">Zoom</class>
			</td>
			<td>
				<select id="TakeImage_CamZoom_value1" onchange="cameraParameterChanged()">
					<option value="true">enabled (true)</option>
					<option value="false" selected>disabled (false)</option>
				</select>			
			</td>
			<td>$TOOLTIP_TakeImage_CamZoom</td>				
			
            <td class="indent1">
                <label id="TakeImage_CamZoomOffsetX_text" style="color:black;">Zoom Offset X: </label>
			</td>
            <td>
                <input required type="number" id="TakeImage_CamZoomOffsetX_value1" value="0" min="-960" max="960" step="8" onchange="cameraParameterChanged()"
                    oninput="(!validity.rangeOverflow||(value=960)) && (!validity.rangeUnderflow||(value=-960)) && (!validity.stepMismatch||(value=parseInt(this.value)));">
            </td>
			<td>$TOOLTIP_TakeImage_CamZoomOffsetX</td>				
        </tr>
		
        <tr class="expert">
            <td class="indent1">
                <label id="TakeImage_CamZoomSize_text" style="color:black;">Zoom Size: </label>
			</td>
            <td>
                <input required type="number" id="TakeImage_CamZoomSize_value1" value="0" min="0" max="59" step="1" onchange="cameraParameterChanged()"
                    oninput="(!validity.rangeOverflow||(value=59)) && (!validity.rangeUnderflow||(value=0)) && (!validity.stepMismatch||(value=parseInt(this.value)));">
            </td>
			<td>$TOOLTIP_TakeImage_CamZoomSize</td>			
		
            <td class="indent1">
                <label id="TakeImage_CamZoomOffsetY_text" style="color:black;">Zoom Offset Y: </label>
			</td>
            <td>
                <input required type="number" id="TakeImage_CamZoomOffsetY_value1" value="0" min="-720" max="720" step="8" onchange="cameraParameterChanged()"
                    oninput="(!validity.rangeOverflow||(value=720)) && (!validity.rangeUnderflow||(value=-720)) && (!validity.stepMismatch||(value=parseInt(this.value)));">
            </td>
			<td>$TOOLTIP_TakeImage_CamZoomOffsetY</td>		
        </tr>
		
        <tr class="expert">
			<td class="indent1">
				<class id="TakeImage_CamSpecialEffect_text" style="color:black;">SpecialEffect: </class>
			</td>
			<td>
				<select id="TakeImage_CamSpecialEffect_value1" onchange="cameraParameterChanged()">
					<option value="no_effect" selected>no effect</option>
					<option value="negative" >negative</option>
					<option value="grayscale" >grayscale</option>					
					<option value="red" >red</option>					
					<option value="green" >green</option>					
					<option value="blue" >blue</option>					
					<option value="retro" >retro</option>					
				</select>
			</td>
			<td>$TOOLTIP_TakeImage_CamSpecialEffect</td>			
			
			<td class="indent1">
				<class id="TakeImage_CamAec2_text" style="color:black;">Auto-exposure Control 2</class>
			</td>
			<td>
				<select id="TakeImage_CamAec2_value1" onchange="cameraParameterChanged()">
					<option value="true">enabled (true)</option>
					<option value="false" selected>disabled (false)</option>
				</select>
			</td>
			<td>$TOOLTIP_TakeImage_CamAec2</td>			
        </tr>
		
        <tr>
			<td class="indent1">
			    <class id="TakeImage_CamHmirror_text" style="color:black;">Mirror Image</class>
			</td>
			<td>
				<select id="TakeImage_CamHmirror_value1" onchange="cameraParameterChanged()">
					<option value="true">enabled (true)</option>
					<option value="false" selected>disabled (false)</option>
				</select>
			</td>			
			<td>$TOOLTIP_TakeImage_CamHmirror</td>
			
            <td class="indent1">
                <class id="TakeImage_LEDIntensity_text" style="color:black;">LED intensity: </class>
            </td>
            <td>
                <input required style="clear: both" type="number" id="TakeImage_LEDIntensity_value1" size="13" value="0"  min="0" max="100" onchange="cameraParameterChanged()" 
                    oninput="(!validity.rangeOverflow||(value=100)) && (!validity.rangeUnderflow||(value=0)) && (!validity.stepMismatch||(value=parseInt(this.value)));">
            </td>
			<td>$TOOLTIP_TakeImage_LEDIntensity</td>
        </tr>
		
        <tr>
			<td class="indent1">
			    <class id="TakeImage_CamVflip_text" style="color:black;">Flip Image</class>
			</td>
			<td>
				<select id="TakeImage_CamVflip_value1" onchange="cameraParameterChanged()">
					<option value="true">enabled (true)</option>
					<option value="false" selected>disabled (false)</option>
				</select>
			</td>			
			<td>$TOOLTIP_TakeImage_CamVflip</td>
			
            <td class="indent1">
                <class id="TakeImage_CamBrightness_text" style="color:black;">Brightness: </class>
            </td>
            <td>
                <input style="clear: both; width: 80%;vertical-align:middle" type="range" id="TakeImage_CamBrightness_value1" size="13" value=0  min="-2" max="2" onchange="cameraParameterChanged()" 
					oninput="this.nextElementSibling.value = this.value">
                <output id="TakeImage_CamBrightness_value1_output" style="vertical-align:middle; min-width:15px; padding-right:5px; text-align:right; float:left">0</output>
            </td>
			<td>$TOOLTIP_TakeImage_CamBrightness</td>
        </tr>
		
        <tr>
            <td class="indent1">
				<label id="PreRotateAngle_text" style="color:black;">Rotation angle:</label>
			</td>
            <td>
                <input required type="number" id="PreRotateAngle_value1" value="0" min="-180" max="180" onchange="cameraParameterChangedDR()"
                    oninput="(!validity.rangeOverflow||(value=180)) && (!validity.rangeUnderflow||(value=-180)) && (!validity.stepMismatch||(value=parseInt(this.value)));">degree
            </td>
			<td>$TOOLTIP_Alignment_InitialRotate</td>
			
            <td class="indent1">
                <class id="TakeImage_CamContrast_text" style="color:black;">Contrast: </class>
            </td>
            <td>
                <input style="clear: both; width: 80%;vertical-align:middle" type="range" id="TakeImage_CamContrast_value1" size="13" value=0  min="-2" max="2" onchange="cameraParameterChanged()" 
					oninput="this.nextElementSibling.value = this.value">
                <output id="TakeImage_CamContrast_value1_output" style="vertical-align:middle; min-width:15px; padding-right:5px; text-align:right; float:left">0</output>
            </td>
			<td>$TOOLTIP_TakeImage_CamContrast</td>
        </tr>
		
        <tr>
            <td class="indent1">
				<label id="FineRotate_text" style="color:black;">(Fine-tune):</label>
			</td>
            <td>
                <input required type="number" id="FineRotate_value1" value=0.0 min="-1" max="1" step="0.1" onchange="cameraParameterChangedDR()"
                    oninput="(!validity.rangeOverflow||(value=1)) && (!validity.rangeUnderflow||(value=-1)) && (!validity.stepMismatch||(value=parseInt(this.value)));">degree
            </td>
			<td></td>
			
            <td class="indent1">
                <class id="TakeImage_CamSaturation_text" style="color:black;">Saturation: </class>
            </td>
            <td>
                <input  style="clear: both; width: 80%;vertical-align:middle" type="range" id="TakeImage_CamSaturation_value1" size="13" value=0 min="-2" max="2" onchange="cameraParameterChanged()" 
					oninput="this.nextElementSibling.value = this.value">
                <output id="TakeImage_CamSaturation_value1_output" style="vertical-align:middle; min-width:15px; padding-right:5px; text-align:right; float:left">0</output>
            </td>
			<td>$TOOLTIP_TakeImage_CamSaturation</td>
        </tr>
		
        <tr class="expert">
			<td class="indent1">
				<class id="TakeImage_CamAec_text" style="color:black;">Auto-exposure Control</class>
			</td>
			<td>
				<select id="TakeImage_CamAec_value1" onchange="cameraParameterChanged()">
					<option value="true">enabled (true)</option>
					<option value="false" selected>disabled (false)</option>
				</select>
			</td>
			<td>$TOOLTIP_TakeImage_CamAec</td>
			
            <td class="indent1">
                <class id="TakeImage_CamAeLevel_text" style="color:black;">Auto Exposure Level: </class>
            </td>
            <td>
                <input  style="clear: both; width: 80%;vertical-align:middle" type="range" id="TakeImage_CamAeLevel_value1" size="13" value=0 min="-2" max="2" onchange="cameraParameterChanged()" 
					oninput="this.nextElementSibling.value = this.value">
                <output id="TakeImage_CamAeLevel_value1_output" style="vertical-align:middle; min-width:15px; padding-right:5px; text-align:right; float:left">0</output>
            </td>
			<td>$TOOLTIP_TakeImage_CamAeLevel</td>
        </tr>
		
        <tr class="expert">
			<td class="indent1">
				<class id="TakeImage_CamAutoSharpness_text" style="color:black;">AutoSharpness</class>
			</td>
			<td>
				<select id="TakeImage_CamAutoSharpness_value1" onchange="cameraParameterChanged()">
					<option value="true">enabled (true)</option>
					<option value="false" selected>disabled (false)</option>
				</select>
			</td>
			<td>$TOOLTIP_TakeImage_CamAutoSharpness</td>			
			
            <td class="indent1">
                <class id="TakeImage_CamSharpness_text" style="color:black;">Sharpness: </class>
            </td>
            <td>
                <input style="clear: both; width: 80%;vertical-align:middle" type="range" id="TakeImage_CamSharpness_value1" size="13" value=0  min="-2" max="2" onchange="cameraParameterChanged()" 
					oninput="this.nextElementSibling.value = this.value">
                <output id="TakeImage_CamSharpness_value1_output" style="vertical-align:middle; min-width:15px; padding-right:5px; text-align:right; float:left">0</output>
            </td>
			<td>$TOOLTIP_TakeImage_CamSharpness</td>
        </tr>
    </table>

    <table>
        <tr class="indent1">
            <td>
				<input class="button" type="submit" id="updatereferenceimage" value="Update Reference Image" onclick="doTakeReference()">
			</td>
			
            <td>
				<input class="button" type="button" id="savereferenceimage" value="Save new Reference Image and Camera Settings" onclick="SaveReference()">
			</td>
        </tr>	
    </table>

    <hr>
    <b>Reference Image:</b><br>
    <canvas id="canvas"></canvas>


    <script type="text/javascript" src="readconfigparam.js?v=$COMMIT_HASH"></script>
    <script type="text/javascript" src="readconfigcommon.js?v=$COMMIT_HASH"></script>

    <script type="text/javascript">
        var canvas = document.getElementById('canvas'),
        domainname = getDomainname(),
        context = canvas.getContext('2d'),
        imageObj = new Image(),
        isActReference = false,
        param,
        category;

        function cameraParameterChanged() {
            document.getElementById("savereferenceimage").disabled = true;

            if(!document.getElementById("TakeImage_CamZoom_value1").selectedIndex) {
				// EnDisableItem(_status, _param, _category, _cat, _name, _optional, _number = -1)
				EnDisableItem(true, param, category, "TakeImage", "CamZoomOffsetX", false);
				EnDisableItem(true, param, category, "TakeImage", "CamZoomOffsetY", false);
				EnDisableItem(true, param, category, "TakeImage", "CamZoomSize", false);				
            }
            else {
				EnDisableItem(false, param, category, "TakeImage", "CamZoomOffsetX", false);
				EnDisableItem(false, param, category, "TakeImage", "CamZoomOffsetY", false);
				EnDisableItem(false, param, category, "TakeImage", "CamZoomSize", false);				
            }

            if(!document.getElementById("TakeImage_CamAutoSharpness_value1").selectedIndex) {
				EnDisableItem(false, param, category, "TakeImage", "CamSharpness", false);				
            }
            else {
				EnDisableItem(true, param, category, "TakeImage", "CamSharpness", false);				
            }			
        }

        function cameraParameterChangedDR() {
            //document.getElementById("savereferenceimage").disabled = true;
            drawRotated();
        }

        // Create New Reference, Update Image
        function doTakeReference(){
            document.getElementById("overlay").style.display = "block";
            document.getElementById("overlaytext").innerHTML = "Taking new image...";
			
			EnDisableItem(true, param, category, "TakeImage", "CamBrightness", false);
			EnDisableItem(true, param, category, "TakeImage", "CamSaturation", false);
			EnDisableItem(true, param, category, "TakeImage", "CamContrast", false);

			EnDisableItem(true, param, category, "TakeImage", "CamAutoSharpness", false);
			
            if(!document.getElementById("TakeImage_CamAutoSharpness_value1").selectedIndex) {
				EnDisableItem(false, param, category, "TakeImage", "CamSharpness", false);				
            }
            else {
				EnDisableItem(true, param, category, "TakeImage", "CamSharpness", false);				
            }			

			EnDisableItem(true, param, category, "TakeImage", "CamZoom", false);
			
            if(!document.getElementById("TakeImage_CamZoom_value1").selectedIndex) {
				EnDisableItem(true, param, category, "TakeImage", "CamZoomOffsetX", false);
				EnDisableItem(true, param, category, "TakeImage", "CamZoomOffsetY", false);
				EnDisableItem(true, param, category, "TakeImage", "CamZoomSize", false);				
            }
            else {
				EnDisableItem(false, param, category, "TakeImage", "CamZoomOffsetX", false);
				EnDisableItem(false, param, category, "TakeImage", "CamZoomOffsetY", false);
				EnDisableItem(false, param, category, "TakeImage", "CamZoomSize", false);				
            }

			EnDisableItem(true, param, category, "TakeImage", "CamAec", false);				
			EnDisableItem(true, param, category, "TakeImage", "CamAec2", false);
			EnDisableItem(true, param, category, "TakeImage", "CamAeLevel", false);
				
			EnDisableItem(true, param, category, "TakeImage", "CamHmirror", false);
			EnDisableItem(true, param, category, "TakeImage", "CamVflip", false);
				
			EnDisableItem(true, param, category, "TakeImage", "CamSpecialEffect", false);
				
			EnDisableItem(true, param, category, "TakeImage", "LEDIntensity", false);			

            document.getElementById("ExpertModus_enabled").disabled = false;

            document.getElementById("FineRotate_value1").disabled = false;
			document.getElementById("FineRotate_text").style.color = "black";
            document.getElementById("PreRotateAngle_value1").disabled = false;
			document.getElementById("PreRotateAngle_text").style.color = "black";

            document.getElementById("showcurrentreference").disabled = false;
            document.getElementById("startreference").disabled = true;
            document.getElementById("updatereferenceimage").disabled = false;
            document.getElementById("savereferenceimage").disabled = false;

            var _aec_temp = document.getElementById("TakeImage_CamAec_value1").selectedIndex;
            if (_aec_temp == '0') {
                _aec_temp = '1';
            }
            else {
                _aec_temp = '0';
            }

            var _aec2_temp = document.getElementById("TakeImage_CamAec2_value1").selectedIndex;
            if (_aec2_temp == '0') {
                _aec2_temp = '1';
            }
            else {
                _aec2_temp = '0';
            }
			
            var _mirror_temp = document.getElementById("TakeImage_CamHmirror_value1").selectedIndex;
            if (_mirror_temp == '0') {
                _mirror_temp = '1';
            }
            else {
                _mirror_temp = '0';
            }
	
            var _flip_temp = document.getElementById("TakeImage_CamVflip_value1").selectedIndex;
            if (_flip_temp == '0') {
                _flip_temp = '1';
            }
            else {
                _flip_temp = '0';
            }		
			
            var _zoom_temp = document.getElementById("TakeImage_CamZoom_value1").selectedIndex;
            if (_zoom_temp == '0') {
                _zoom_temp = '1';
            }
            else {
                _zoom_temp = '0';
            }			
			
            var _ashp_temp = document.getElementById("TakeImage_CamAutoSharpness_value1").value;
            if (_ashp_temp == '0') {
                _ashp_temp = '1';
            }
            else {
                _ashp_temp = '0';
            }
			
            var _zoomx_temp = document.getElementById("TakeImage_CamZoomOffsetX_value1").value;
            var _zoomy_temp = document.getElementById("TakeImage_CamZoomOffsetY_value1").value;
            var _zooms_temp = document.getElementById("TakeImage_CamZoomSize_value1").value;
			
            var _ledi_temp = document.getElementById("TakeImage_LEDIntensity_value1").value;			
                
            var _bri_temp = document.getElementById("TakeImage_CamBrightness_value1").value;
            var _con_temp = document.getElementById("TakeImage_CamContrast_value1").value;
            var _sat_temp = document.getElementById("TakeImage_CamSaturation_value1").value;
            var _shp_temp = document.getElementById("TakeImage_CamSharpness_value1").value;

            var _ael_temp = document.getElementById("TakeImage_CamAeLevel_value1").value;
            var _effect_temp = document.getElementById("TakeImage_CamSpecialEffect_value1").selectedIndex;
			
            var url = domainname + "/editflow?task=test_take";
			
            if (domainname.length > 0) {
                url = url + "&host=" + domainname;
            }
			
            url = url + "&bri=" + _bri_temp + "&con=" + _con_temp + "&sat=" + _sat_temp + "&shp=" + _shp_temp;
            url = url + "&ashp=" + _ashp_temp + "&ledi=" + _ledi_temp + "&spe=" + _effect_temp + "&zoom=" + _zoom_temp;
                
            if (_zoom_temp != '0') {
				url = url + "&zooms=" + _zooms_temp + "&zoomx=" + _zoomx_temp + "&zoomy=" + _zoomy_temp;
            }
            else {
                url = url + "&zooms=0" + "&zoomx=0" + "&zoomy=0";
            }		    
                    
            url = url + "&aec=" + _aec_temp + "&ael=" + _ael_temp + "&aec2=" + _aec2_temp;
            url = url + "&mirror=" + _mirror_temp + "&flip=" + _flip_temp;			

            var durchlaufe = 0;

            function sleep(ms) {
                return new Promise(resolve => setTimeout(resolve, ms));
            }

            async function task() {
                while (true) {
                    var xhttp = new XMLHttpRequest();
					
                    if (durchlaufe > 10) {
						document.getElementById("overlay").style.display = "none";
                        firework.launch('Image capture aborted, timeout!', 'danger', 5000);
                        return;
                    }					

                    try {
                        xhttp.open("GET", url, false);
                        xhttp.send();
                    } catch (error){}				
            
                    if (xhttp.responseText != "DeviceIsBusy") {
                        var _url = domainname + "/img_tmp/raw.jpg" + "?session=" + Math.floor((Math.random() * 1000000) + 1);						
                        loadCanvas(_url, true);
                        isActReference = false;
						
                        document.getElementById("overlay").style.display = "none";
                        firework.launch('Image capture completed, please wait until it loads...', 'success', 5000);

                        return;
                    }
                    else {
                        // Get status
                        var _xhttp = new XMLHttpRequest();
						durchlaufe = durchlaufe + 1;
						
                        try {
                            _xhttp.open("GET", domainname + "/statusflow", false);
                            _xhttp.send();
                        }
                        catch (error){}

                        document.getElementById("overlaytext").innerHTML = "Device is busy, please wait.<br><br>Current step: " + _xhttp.responseText;
                        console.log("Device is busy, waiting 5s then checking again...");
                        await sleep(2000);
                    }
                }
            }

            setTimeout(function() { 
                // Delay so the overlay gets shown
                task();
            }, 1);
        }

        function camSettingsSet(){
            document.getElementById("overlay").style.display = "block";
            document.getElementById("overlaytext").innerHTML = "Save Cam Settings...";			

            var _aec_temp = document.getElementById("TakeImage_CamAec_value1").selectedIndex;
            if (_aec_temp == '0') {
                _aec_temp = '1';
            }
            else {
                _aec_temp = '0';
            }

            var _aec2_temp = document.getElementById("TakeImage_CamAec2_value1").selectedIndex;
            if (_aec2_temp == '0') {
                _aec2_temp = '1';
            }
            else {
                _aec2_temp = '0';
            }
			
            var _mirror_temp = document.getElementById("TakeImage_CamHmirror_value1").selectedIndex;
            if (_mirror_temp == '0') {
                _mirror_temp = '1';
            }
            else {
                _mirror_temp = '0';
            }
	
            var _flip_temp = document.getElementById("TakeImage_CamVflip_value1").selectedIndex;
            if (_flip_temp == '0') {
                _flip_temp = '1';
            }
            else {
                _flip_temp = '0';
            }		
			
            var _zoom_temp = document.getElementById("TakeImage_CamZoom_value1").selectedIndex;
            if (_zoom_temp == '0') {
                _zoom_temp = '1';
            }
            else {
                _zoom_temp = '0';
            }			

            var _ashp_temp = document.getElementById("TakeImage_CamAutoSharpness_value1").value;
            if (_ashp_temp == '0') {
                _ashp_temp = '1';
            }
            else {
                _ashp_temp = '0';
            }

            var _zoomx_temp = document.getElementById("TakeImage_CamZoomOffsetX_value1").value;
            var _zoomy_temp = document.getElementById("TakeImage_CamZoomOffsetY_value1").value;
            var _zooms_temp = document.getElementById("TakeImage_CamZoomSize_value1").value;
			
            var _ledi_temp = document.getElementById("TakeImage_LEDIntensity_value1").value;
                
            var _bri_temp = document.getElementById("TakeImage_CamBrightness_value1").value;
            var _con_temp = document.getElementById("TakeImage_CamContrast_value1").value;
            var _sat_temp = document.getElementById("TakeImage_CamSaturation_value1").value;
            var _shp_temp = document.getElementById("TakeImage_CamSharpness_value1").value;

            var _ael_temp = document.getElementById("TakeImage_CamAeLevel_value1").value;
            var _effect_temp = document.getElementById("TakeImage_CamSpecialEffect_value1").selectedIndex;

            var url = domainname + "/editflow?task=cam_settings";

            if (domainname.length > 0) {
                url = url + "&host=" + domainname;
            }

            url = url + "&bri=" + _bri_temp + "&con=" + _con_temp + "&sat=" + _sat_temp + "&shp=" + _shp_temp;
            url = url + "&ashp=" + _ashp_temp + "&ledi=" + _ledi_temp + "&spe=" + _effect_temp + "&zoom=" + _zoom_temp;

            if (_zoom_temp != '0') {
				url = url + "&zooms=" + _zooms_temp + "&zoomx=" + _zoomx_temp + "&zoomy=" + _zoomy_temp;
            }
            else {
                url = url + "&zooms=0" + "&zoomx=0" + "&zoomy=0";
            }		    

            url = url + "&aec=" + _aec_temp + "&ael=" + _ael_temp + "&aec2=" + _aec2_temp;
            url = url + "&mirror=" + _mirror_temp + "&flip=" + _flip_temp;			

            var durchlaufe = 0;

            function sleep(ms) {
                return new Promise(resolve => setTimeout(resolve, ms));
            }

            async function task() {
                while (true) {
                    var xhttp = new XMLHttpRequest();
					
                    if (durchlaufe > 10) {
						document.getElementById("overlay").style.display = "none";
                        firework.launch('Save Cam Settings aborted, timeout!', 'danger', 5000);
                        return;
                    }					

                    try {
                        xhttp.open("GET", url, false);
                        xhttp.send();
                    } catch (error){}				
            
                    if (xhttp.responseText == "CamSettingsSet") {
						document.getElementById("overlay").style.display = "none";
                        firework.launch('Cam Settings saved', 'success', 5000);
                        return;
                    }
                    else {
                        // Get status
                        var _xhttp = new XMLHttpRequest();
						durchlaufe = durchlaufe + 1;
						
                        try {
                            _xhttp.open("GET", domainname + "/statusflow", false);
                            _xhttp.send();
                        }
                        catch (error){}

                        document.getElementById("overlaytext").innerHTML = "Device is busy, plase waiting...<br><br>Current step: " + _xhttp.responseText;
                        console.log("Device is busy, waiting 2s then checking again...");
                        await sleep(2000);
                    }
                }
            }

            setTimeout(function() { 
                // Delay so the overlay gets shown
                task();
            }, 1);
        }
		
        function showReference(){
            url = domainname + "/fileserver/config/reference.jpg" + "?session=" + Math.floor((Math.random() * 1000000) + 1);		
            loadCanvas(url, false);
            isActReference = true;			
		
            var _rotate_temp = param["Alignment"]["InitialRotate"].value1;

            if (_rotate_temp < 0) {
                document.getElementById("PreRotateAngle_value1").value = Math.ceil(_rotate_temp);
            }
            else {
                document.getElementById("PreRotateAngle_value1").value = Math.floor(_rotate_temp);
            }

            document.getElementById("FineRotate_value1").value = (Number(_rotate_temp) - Number(document.getElementById("PreRotateAngle_value1").value)).toFixed(1);

			WriteParameter(param, category, "TakeImage", "CamBrightness", false, true);
			WriteParameter(param, category, "TakeImage", "CamContrast", false, true);
			WriteParameter(param, category, "TakeImage", "CamSaturation", false, true);
			WriteParameter(param, category, "TakeImage", "CamSharpness", false, true);
			WriteParameter(param, category, "TakeImage", "CamAutoSharpness", false);

			WriteParameter(param, category, "TakeImage", "CamZoom", false);
			WriteParameter(param, category, "TakeImage", "CamZoomOffsetX", false);
			WriteParameter(param, category, "TakeImage", "CamZoomOffsetY", false);
			WriteParameter(param, category, "TakeImage", "CamZoomSize", false);			

			WriteParameter(param, category, "TakeImage", "CamAec", false);	
			WriteParameter(param, category, "TakeImage", "CamAec2", false);
			WriteParameter(param, category, "TakeImage", "CamAeLevel", false, true);
			
			WriteParameter(param, category, "TakeImage", "CamHmirror", false);
			WriteParameter(param, category, "TakeImage", "CamVflip", false);
			
			WriteParameter(param, category, "TakeImage", "CamSpecialEffect", false);
			
			WriteParameter(param, category, "TakeImage", "LEDIntensity", false);

			EnDisableItem(false, param, category, "TakeImage", "CamBrightness", false);
			EnDisableItem(false, param, category, "TakeImage", "CamSaturation", false);
			EnDisableItem(false, param, category, "TakeImage", "CamContrast", false);
			EnDisableItem(false, param, category, "TakeImage", "CamSharpness", false);
			EnDisableItem(false, param, category, "TakeImage", "CamAutoSharpness", false);

			EnDisableItem(false, param, category, "TakeImage", "CamZoom", false);
			EnDisableItem(false, param, category, "TakeImage", "CamZoomOffsetX", false);
			EnDisableItem(false, param, category, "TakeImage", "CamZoomOffsetY", false);
			EnDisableItem(false, param, category, "TakeImage", "CamZoomSize", false);			

			EnDisableItem(false, param, category, "TakeImage", "CamAec", false);				
			EnDisableItem(false, param, category, "TakeImage", "CamAec2", false);
			EnDisableItem(false, param, category, "TakeImage", "CamAeLevel", false);
				
			EnDisableItem(false, param, category, "TakeImage", "CamHmirror", false);
			EnDisableItem(false, param, category, "TakeImage", "CamVflip", false);
				
			EnDisableItem(false, param, category, "TakeImage", "CamSpecialEffect", false);
				
			EnDisableItem(false, param, category, "TakeImage", "LEDIntensity", false);			
			
            document.getElementById("ExpertModus_enabled").disabled = true;
			
            document.getElementById("FineRotate_value1").disabled = true;
			document.getElementById("FineRotate_text").style.color = "rgb(122, 122, 122)";
            document.getElementById("PreRotateAngle_value1").disabled = true;
			document.getElementById("PreRotateAngle_text").style.color = "rgb(122, 122, 122)"; 
			
            document.getElementById("savereferenceimage").disabled = true;
            document.getElementById("updatereferenceimage").disabled = true;
            document.getElementById("showcurrentreference").disabled = true;
            document.getElementById("startreference").disabled = false;                                  
        }

        function SaveReference(){
            param["Alignment"]["InitialRotate"].value1 = (Number(document.getElementById("PreRotateAngle_value1").value) + 
                                                            Number(document.getElementById("FineRotate_value1").value)).toFixed(1);

			ReadParameter(param, "TakeImage", "CamBrightness", false);
			ReadParameter(param, "TakeImage", "CamContrast", false);
			ReadParameter(param, "TakeImage", "CamSaturation", false);
			ReadParameter(param, "TakeImage", "CamSharpness", false);
			ReadParameter(param, "TakeImage", "CamAutoSharpness", false);

			ReadParameter(param, "TakeImage", "CamZoom", false);
			ReadParameter(param, "TakeImage", "CamZoomOffsetX", false);
			ReadParameter(param, "TakeImage", "CamZoomOffsetY", false);
			ReadParameter(param, "TakeImage", "CamZoomSize", false);			

			ReadParameter(param, "TakeImage", "CamAec", false);	
			ReadParameter(param, "TakeImage", "CamAec2", false);
			ReadParameter(param, "TakeImage", "CamAeLevel", false);
			
			ReadParameter(param, "TakeImage", "CamHmirror", false);
			ReadParameter(param, "TakeImage", "CamVflip", false);
			
			ReadParameter(param, "TakeImage", "CamSpecialEffect", false);
			
			ReadParameter(param, "TakeImage", "LEDIntensity", false);			

            var canvas = document.getElementById("canvas");
            drawRotated(false);

            WriteConfigININew();
            SaveConfigToServer(domainname);    

            SaveCanvasToImage(canvas, "/config/reference.jpg", true, domainname);
            				
            camSettingsSet();
            
            showReference();				
            firework.launch('Reference image configuration saved', 'success', 5000);
        }

        function init() {
            openDescription();		
	
            if (!loadConfig(domainname)) {
				firework.launch('Configuration could not be loaded! Please reload the page!', 'danger', 30000);
				return;
            }		
			
            param = getCamConfig();
			category = getConfigCategory();
			
			canvas.addEventListener('mousemove', mouseMove, false);			

            UpdateExpertModus();
			UpdateTooltipModus();
            showReference();
        }

        function loadCanvas(dataURL, grid = false) {
            var canvas = document.getElementById('canvas');
            var context = canvas.getContext('2d');

            console.log("loadCanvas");
        
            imageObj.onload = function() {
                canvas.width = this.width;
                canvas.height = this.height;
                
                if (grid) {
                    drawRotated(true);
                }
                else {
                    drawRotated(false);
                }

                console.log("Done");
                document.getElementById("overlay").style.display = "none";

            };

            imageObj.src = dataURL;
        }

        function SaveCanvasToImage(_canvas, _filename, _delete = true, _domainname = ""){
            var JPEG_QUALITY=0.8;
            var dataUrl = _canvas.toDataURL('image/jpeg', JPEG_QUALITY);	
            var rtn = dataURLtoBlob(dataUrl);

            if (_delete) {
                FileDeleteOnServer(_filename, _domainname);
            }

            FileSendContent(rtn, _filename, _domainname);
        }

        function dataURLtoBlob(dataurl) {
            var arr = dataurl.split(',');
            var mime = arr[0].match(/:(.*?);/)[1];
            var bstr = atob(arr[1]);
            var n = bstr.length;
            var u8arr = new Uint8Array(n);
				
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
			
            return new Blob([u8arr], {type:mime});
        }

        function drawRotated(_grid = true) {
            var canvas = document.getElementById('canvas');
            var context = canvas.getContext('2d');		
		
            var _finerot = parseFloat(document.getElementById("FineRotate_value1").value);
            var _prerot = parseFloat(document.getElementById("PreRotateAngle_value1").value);
			
            if (_finerot == 1) {
                _prerot+=1
                _finerot = 0
            }
			
            if (_finerot == -1) {
                _prerot-=1
                _finerot = 0
            }
			
            degrees = _finerot + _prerot;
            document.getElementById("FineRotate_value1").value =  _finerot;
            document.getElementById("PreRotateAngle_value1").value =  _prerot;
			
            canvas.width = imageObj.width;
            canvas.height = imageObj.height;

            context.clearRect(0,0,canvas.width,canvas.height);
            context.save();

            if (isActReference) {
                context.drawImage(imageObj,0,0);
            }
            else {
                context.translate(canvas.width/2,canvas.height/2);
                context.rotate(degrees*Math.PI/180);
				
                context.drawImage(imageObj,-imageObj.width/2,-imageObj.height/2);
            }
            
            context.restore();

            if (_grid) {
                drawGrid();
            }
        }

        function drawGrid(){
            var canvas = document.getElementById('canvas');
            var context = canvas.getContext('2d');
			
            var w = canvas.width;
            var h = canvas.height;
            context.save();
            context.strokeStyle = '#00FF00';

            for (i = h/2; i < h; i += 100) {
                context.moveTo(0, i);
                context.lineTo(w, i);
                context.stroke();
                context.moveTo(0, h-i);
                context.lineTo(w, h-i);
                context.stroke();
            }
			
            for (i = w/2; i < w; i += 100) {
                context.moveTo(i, 0);
                context.lineTo(i, h);
                context.stroke();
                context.moveTo(w-i, 0);
                context.lineTo(w-i, h);
                context.stroke();                
            }
			
            context.restore();
        }

        function mouseMove(e) {
            var canvas = document.getElementById('canvas');
            var context = canvas.getContext('2d');            
			
            if (isActReference) {
                drawRotated(false);
            }
            else {
                drawRotated(true);
            }
            
            var zw = getCoords(this);
            var x = e.pageX - zw.left;
            var y = e.pageY - zw.top;
            
            context.lineWidth = 2;
            context.strokeStyle = "#00FF00";
            context.beginPath(); 
            context.moveTo(0,y);
            context.lineTo(canvas.width, y);
            context.moveTo(x, 0);
            context.lineTo(x, canvas.height);
            context.stroke();            
        }

        function UpdateExpertModus() {
            var _style_pur = 'none';
            var _hidden = true;
			
            if (document.getElementById("ExpertModus_enabled").checked) {
                _style_pur = '';
                _hidden = false;
                firework.launch("Expert parameter view activated. Please use it carefully", 'warning', 5000);
            }

            const expert = document.querySelectorAll(".expert");
			
            for (var i = 0; i < expert.length; i++) {
                expert[i].style.display = _style_pur;
            }
        }
		
		function UpdateTooltipModus() {
			var _style_pur = 'none';
			var _hidden = true;

			if (param["System"]["Tooltip"].value1 == 'true') {
				_style_pur = '';
				_hidden = false;
			}

			const tooltip = document.querySelectorAll(".tooltip");
	
			for (var i = 0; i < tooltip.length; i++) {
				tooltip[i].style.display = _style_pur;
			}
		}		

        function getCoords(elem) { 
            // crossbrowser version
            var box = elem.getBoundingClientRect();
            var body = document.body;
            var docEl = document.documentElement;
            var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
            var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft;
            var clientTop = docEl.clientTop || body.clientTop || 0;
            var clientLeft = docEl.clientLeft || body.clientLeft || 0;
            var top  = box.top +  scrollTop - clientTop;
            var left = box.left + scrollLeft - clientLeft;
			
            return { top: Math.round(top), left: Math.round(left) };
        }

		function InvertEnableItem(_cat, _param) {
			_zw = _cat + "_" + _param + "_enabled";
			_isOn = document.getElementById(_zw).checked;

			_color = "rgb(122, 122, 122)";
	
			if (_isOn) {
				_color = "black";
			}

			_zw = _cat + "_" + _param + "_text";
			document.getElementById(_zw).disabled = !_isOn;
			document.getElementById(_zw).style.color = _color;

			setEnabled(_cat + "_" + _param, _isOn);

			for (var j = 1; j <= param[_cat][_param]["anzParam"]; ++j) {
				document.getElementById(_cat+"_"+_param+"_value"+j).disabled = !_isOn;	
				document.getElementById(_cat+"_"+_param+"_value"+j).style.color = _color;
			}
		}

		function setEnabled(className, enabled) {
			_color = "rgb(122, 122, 122)";
	
			if (enabled) {
				_color = "black";
			}

			let elements = document.getElementsByClassName(className);
	
			for (i = 0; i < elements.length; i++) {
				if (enabled) {
					elements[i].classList.remove("disabled");
				} 
				else {
					elements[i].classList.add("disabled");
				}

				let inputs = elements[i].getElementsByTagName("input");
		
				for (j = 0; j < inputs.length; j++) {
					if (inputs[j].id.endsWith("_enabled")) {
						continue;
					}

					inputs[j].style.color = _color;
			
					if (enabled) {
						inputs[j].removeAttribute("disabled");
					} 
					else {
						inputs[j].setAttribute("disabled", "disabled");
					}
				}
			}
		}

		function setVisible(className, visible) {
			let elements = document.getElementsByClassName(className);
	
			for (i = 0; i < elements.length; i++) {
				if (visible) {
					elements[i].classList.remove("hidden");
				} 
				else {
					elements[i].classList.add("hidden");
				}
			}
		}

		function EnDisableItem(_status, _param, _category, _cat, _name, _optional, _number = -1) {
			//_status = _category[_cat]["enabled"];

			_color = "rgb(122, 122, 122)";
	
			if (_status) {
				_color = "black";
			}

			if (_optional) {
				document.getElementById(_cat+"_"+_name+"_enabled").disabled = !_status;
				document.getElementById(_cat+"_"+_name+"_enabled").style.color = _color;	
			}

			if (_number == -1) {
				if (!_param[_cat][_name]["enabled"]) {
					_status = false;
					_color = "rgb(122, 122, 122)";
				}
			}
			else {
				if (!NUMBERS[_number][_cat][_name]["enabled"]) {
					_status = false;
					_color = "rgb(122, 122, 122)";
				}
			}

			document.getElementById(_cat+"_"+_name+"_text").disabled = !_status;
			document.getElementById(_cat+"_"+_name+"_text").style.color = _color;

			setEnabled(_cat+"_"+_name, _status);

			for (var j = 1; j <= _param[_cat][_name]["anzParam"]; ++j) {
				document.getElementById(_cat+"_"+_name+"_value"+j).disabled = !_status;	
				document.getElementById(_cat+"_"+_name+"_value"+j).style.color = _color;	
			}
		}

		function ReadParameter(_param, _cat, _name, _optional, _number = -1) {
			if (_number > -1) {
				if (_cat == "Digits") {
					_cat = "digit";
				}
	    
				if (_cat == "Analog") {
					_cat = "analog";
				}

				if ((NUMBERS[_number] == undefined) || (NUMBERS[_number][_cat] == undefined) ||  (NUMBERS[_number][_cat][_name] == undefined)) {
					return;
				}

				if (_optional) {
					NUMBERS[_number][_cat][_name]["enabled"] = document.getElementById(_cat+"_"+_name+"_enabled").checked;			
				}

				for (var j = 1; j <= _param[_cat][_name]["anzParam"]; ++j) {
					let element = document.getElementById(_cat+"_"+_name+"_value"+j);
					
					if (element.tagName.toLowerCase() == "select") {
						NUMBERS[_number][_cat][_name]["value"+j] = element.selectedIndex > -1 ? element.options[element.selectedIndex].value : "";
					}
					else if ((element.getAttribute("type") != null) && (element.getAttribute("type").toLowerCase() == "checkbox")) {
						NUMBERS[_number][_cat][_name]["value"+j] = element.checked;
					}
					else {
						if ((NUMBERS[_number][_cat][_name].checkRegExList != null) && (NUMBERS[_number][_cat][_name].checkRegExList[j-1] != null)) {
							if (!element.value.match(NUMBERS[_cat][_name].checkRegExList[j-1])) {
								element.classList.add("invalid-input");
							} 
							else {
								element.classList.remove("invalid-input");
							}
						}
						NUMBERS[_number][_cat][_name]["value"+j] = element.value;
					}
				}
			}
			else {
				if (_optional) {
					_param[_cat][_name]["enabled"] = document.getElementById(_cat+"_"+_name+"_enabled").checked;			
				}

				for (var j = 1; j <= _param[_cat][_name]["anzParam"]; ++j) {
					let element = document.getElementById(_cat+"_"+_name+"_value"+j);
					
					if (element.tagName.toLowerCase() == "select") {
						_param[_cat][_name]["value"+j] = element.selectedIndex > -1 ? element.options[element.selectedIndex].value : "";
					}
					else if ((element.getAttribute("type") != null) && (element.getAttribute("type").toLowerCase() == "checkbox")) {
						_param[_cat][_name]["value"+j] = element.checked;
					}
					else {
						if ((_param[_cat][_name].checkRegExList != null) && (_param[_cat][_name].checkRegExList[j-1] != null)) {
							if (!element.value.match(_param[_cat][_name].checkRegExList[j-1])) {
								element.classList.add("invalid-input");
							} 
							else {
								element.classList.remove("invalid-input");
							}
						}
						_param[_cat][_name]["value"+j] = element.value;
					}
				}		
			}
		}

		function WriteParameter(_param, _category, _cat, _name, _optional, _outval = false, _number = -1) {
			let anzpara;
			try {
				anzpara = _param[_cat][_name].anzParam;	
			}
			catch (error) {
				firework.launch("Parameter '" + _name + "' in der Kategorie '" + _cat + "' ist unbekannt!", 'danger', 30000);
				return;
			}

			if (_number > -1) {
				if ((NUMBERS[_number] == undefined) || (NUMBERS[_number][_cat] == undefined) ||  (NUMBERS[_number][_cat][_name] == undefined)) {
					return;
				}

				if (_optional) {
					document.getElementById(_cat+"_"+_name+"_enabled").checked = NUMBERS[_number][_cat][_name]["enabled"];
					
					for (var j = 1; j <= anzpara; ++j) {
						document.getElementById(_cat+"_"+_name+"_value"+j).disabled = !NUMBERS[_number][_cat][_name]["enabled"];	
					}		
				}
	    
				document.getElementById(_cat+"_"+_name+"_text").style.color = "black"
				setEnabled(_cat+"_"+_name, true);

				for (var j = 1; j <= anzpara; ++j) {
					let element = document.getElementById(_cat+"_"+_name+"_value"+j);
					
					if (element.tagName.toLowerCase() == "select") {
						var textToFind = NUMBERS[_number][_cat][_name]["value"+j];
						
						if (textToFind == undefined) {
							continue;
						}

						_isFound = false;
						element.selectedIndex = -1;
						
						for (var i = 0; i < element.options.length; i++) {
							if (element.options[i].value.toLowerCase() === textToFind.toLowerCase()) {
								element.selectedIndex = i;
								_isFound = true;
								break;
							}
						}
						
						if (!_isFound) {
							_zw_txt = "Der Wert '" + textToFind + "' des Parameters '" + _name;
							_zw_txt = _zw_txt + "' im Bereich '" + _cat + "' ist ungültig. BITTE VOR DEM SPEICHERN PRÜFEN!";
							firework.launch(_zw_txt, 'warning', 10000);
						}
					}
					else if ((element.getAttribute("type") != null) && (element.getAttribute("type").toLowerCase() == "checkbox")) {
						element.checked = NUMBERS[_number][_cat][_name]["value"+j] == "true";
					}
					else {
						element.value = NUMBERS[_number][_cat][_name]["value"+j];
					}
				}
				
                if (_outval) {
					for (var j = 1; j <= anzpara; ++j) {				
						document.getElementById(_cat+"_"+_name+"_value"+j+"_output").value = document.getElementById(_cat+"_"+_name+"_value"+j).value;
					}
				}				
			}
			else {
				if (_optional) {
					document.getElementById(_cat+"_"+_name+"_enabled").checked = _param[_cat][_name]["enabled"];
					
					for (var j = 1; j <= anzpara; ++j) {
						document.getElementById(_cat+"_"+_name+"_value"+j).disabled = !_param[_cat][_name]["enabled"];	
					}		
				}

				document.getElementById(_cat+"_"+_name+"_text").style.color = "black"
				setEnabled(_cat+"_"+_name, true);

				for (var j = 1; j <= anzpara; ++j) {
					let element = document.getElementById(_cat+"_"+_name+"_value"+j);
					
					if (element.tagName.toLowerCase() == "select") {
						var textToFind = _param[_cat][_name]["value"+j];
						
						if (textToFind == undefined) {
							continue;
						}
                
						_isFound = false;
						element.selectedIndex = -1;
						
						for (var i = 0; i < element.options.length; i++) {
							if (element.options[i].value.toLowerCase() === textToFind.toLowerCase()) {
								element.selectedIndex = i;
								_isFound = true;
								break;
							}
						}
						
						if (!_isFound) {
							_zw_txt = "Der Wert '" + textToFind + "' des Parameters '" + _name;
							_zw_txt = _zw_txt + "' im Bereich '" + _cat + "' ist ungültig. BITTE VOR DEM SPEICHERN PRÜFEN!";
							firework.launch(_zw_txt, 'warning', 10000);
						}

					}
					else if ((element.getAttribute("type") != null) && (element.getAttribute("type").toLowerCase() == "checkbox")) {
						element.checked = _param[_cat][_name]["value"+j] == "true";
					}
					else {
						element.value = _param[_cat][_name]["value"+j];
					}
				}

                if (_outval) {
                    document.getElementById(_cat+"_"+_name+"_value1_output").value = document.getElementById(_cat+"_"+_name+"_value1").value;
				}				
			}

			///////////////// am Ende, falls Kategorie als gesamtes nicht ausgewählt --> deaktivieren
			if (_category[_cat]["enabled"] == false) {
				if (_optional) {
					document.getElementById(_cat+"_"+_name+"_enabled").disabled = true;
					
					for (var j = 1; j <= anzpara; ++j) {
						document.getElementById(_cat+"_"+_name+"_value"+j).disabled = true;
					}	
				}
				
				document.getElementById(_cat+"_"+_name+"_text").style="color: gray;"
				setEnabled(_cat+"_"+_name, false);
			}

			EnDisableItem(_category[_cat]["enabled"], _param, _category, _cat, _name, _optional, _number);
		}

        /* hash #description open the details part of the page */
        function openDescription() {
            if(window.location.hash) {
                var hash = window.location.hash.substring(1);
				
                if(hash == 'description') {
                    document.getElementById("desc_details").open = true;
                }
            }
        }

        init();

    </script>
</body>
</html>
